package com.cp.mtq.utils;

import cn.hutool.core.date.DateUtil;
import com.cp.mtq.exception.MtqException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
public class FileUtil {

    public static String localUpload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String key = UUID.randomUUID().toString().replace("-", "") + suffix;
        String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String path = "/apps/mtq" + "/" + day;
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File f = new File(path + "/" + key);
        if(f.exists()){
            throw new MtqException("文件名已存在");
        }
        try {
            file.transferTo(f);
            return path + "/" + key;
        } catch (IOException e) {
            log.error(e.toString());
            throw new MtqException("上传文件出错");
        }
    }
}
